import fs from "fs";
import { NextRequest, NextResponse } from "next/server";
import dayjs from "dayjs";
import path from "path";
import { handlerApi } from "@/lib/handlerApi";
const getFielData = async (file: File) => {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      // 读取文件内容
      const data = event.target!.result;

      resolve(data);
    };
    reader.readAsText(file);
  });
};
const saveFile = async (blob: File) => {
  const timeDir = dayjs().format("YYYY-MM-DD");
  const uploadDir = process.env.FILE_STORE + timeDir;
  fs.mkdirSync(uploadDir, {
    recursive: true,
  });
  const type = blob.type.split("/")[1];
  const fileName = new Date().getTime().toString() + "." + type;
  const buffer = Buffer.from(await blob.arrayBuffer());

  fs.writeFileSync(path.join(uploadDir, fileName), buffer as any);
  return `${process.env.IMAGE_PREX}/${timeDir}/${fileName}`;
};

export const dynamic = "force-dynamic"; // defaults to auto
const uploadImg = handlerApi(async (req: NextRequest) => {
  const formData = await req.formData();
  const file: File = formData.get("file") as File;
  // console.log(file);
  if (!file) {
    throw Error("No files received.");
  }

  const result = await saveFile(file);
  // const res = await sharp().com.toFile('./ceshi.png');
  // return process.env.FILE_STORE;
  return result;
});
export const POST = uploadImg;
